<?php

namespace app\admin\controller;


use app\common\exception\ApiException;
use app\common\lib\qiniuUpload;

class Image extends BaseController {
    public function uploadToLocal() {
        $file = request()->file('file');
        $info = $file->move('upload');
        if ($info && $info->getPathname()) {
            $imgModel = model('Images');
            $imgModel->save([
                'url' => $info->getPathname()
            ]);
            return show(config('code.success'), '上传成功', [
                'url'    => $info->getPathname(),
                'img_id' => $imgModel->getLastInsID()
            ]);
        }
        return show(config('code.fail'), '上传失败');
    }

    public function uploadToQiNiu() {
        $url  = model('Images')->uploadToQiniu();
        $data = input('post.');
        if ($url) {
            $data['url']  = $url;
            $data['from'] = config('code.from_online');
            $id           = model('Images')->add($data);
            return show(0, 'OK', [
                'url'    => $data['url'],
                'img_id' => $id
            ]);
        }
        return show(1, '上传失败');
    }

    public function deleteImage() {
        $url = input('post.url');
//        $condition['url'] = str_replace('\\\\', '\\', getUploadUrl($url));
        $condition['url'] = getUploadUrl($url);
        $result1          = model('Images')->where($condition)
            ->delete();
        $result2          = unlink($condition['url']);
        return show(0, 'delete success', ['database' => $result1, 'upload' => $result2]);
    }

    public function deleteQiniuImage() {
        $url     = input('post.url');
        $result1 = model('Images')
            ->where(['url' => $url])
            ->delete();
        return show(0, 'delete success', ['database' => $result1]);

    }
}